package com.xsherl.leetcode.solution;

public class StringToInteger {

    public int myAtoi(String s) {
        int res = 0, factor = 1;
        int i = 0;
        while (i < s.length() && s.charAt(i) == ' '){
            ++i;
        }
        if (i == s.length()){
            return 0;
        }
        if (s.charAt(i) == '-'){
            factor = -1;
            ++i;
        } else if (s.charAt(i) == '+'){
            ++i;
        }
        for ( ;i < s.length(); ++i){
            char c = s.charAt(i);
            if (c < '0' || c > '9'){
                break;
            }
            int residue = c - '0';
            if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && residue > 7)){
                return Integer.MAX_VALUE;
            }
            if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && residue > 8)){
                return Integer.MIN_VALUE;
            }
            res = res * 10 + residue * factor;
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "-91283472332";
        int i = new StringToInteger().myAtoi(s);
        System.out.println((int)-91283472332L);
        System.out.println(i);
    }

}
